package com.diankangwo.controller;

import cn.beecloud.BCCache;
import com.alibaba.fastjson.JSONObject;
import com.diankangwo.service.WebHookService;
import com.diankangwo.util.BeecloudPayUtil;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;

/**
 * web hook 用于beecloud服务器与部署服务器通信,处理[支付|退款]相关订单日志状态 此Controller无需人为干预,谨慎修改代码
 */

@Controller
@RequestMapping("/webhook")
public class WebhookController {

    @Autowired
    private WebHookService webHookService;

    Logger log = Logger.getLogger(this.getClass());

    byte[] getContentBytes(String content, String charset) {
        if (charset == null || "".equals(charset)) {
            return content.getBytes();
        }
        try {
            return content.getBytes(charset);
        } catch (Exception e) {
            throw new RuntimeException("MD5签名过程中出现错误，指定的编码集不正确,目前指定的编码集是" + charset);
        }
    }

    boolean verifySing(String sign, String timestamp) {
        log.info("sign :" + sign);
        log.info("timestamp :" + timestamp);
        return verify(sign, BCCache.getAppID() + BCCache.getAppSecret(), timestamp, "UTF-8");
    }

    boolean verify(String sign, String text, String key, String input_charset) {
        text = text + key;
        String mysign = DigestUtils.md5Hex(getContentBytes(text, input_charset));
        log.info("mysign :" + mysign);

        long timeDifference = System.currentTimeMillis() - Long.valueOf(key);
        log.info("timeDifference :" + timeDifference);
        if (mysign.equals(sign) && timeDifference <= 300000) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * beecloud支付消息推送机制
     *
     * @param request
     * @param response
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/notifyUrl", method = RequestMethod.POST, produces = "application/json")
    public @ResponseBody
    Object notifyUrl(HttpServletRequest request, HttpServletResponse response) throws IOException {
        BeecloudPayUtil.registerApp();
        StringBuffer json = new StringBuffer();
        String line = null;
        try {
            BufferedReader reader = request.getReader();
            while ((line = reader.readLine()) != null) {
                json.append(line);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        JSONObject jsonObj = JSONObject.parseObject(json.toString());

        if (null == jsonObj) {
            return null;
        }
        String sign = jsonObj.getString("sign");
        String timestamp = jsonObj.getString("timestamp");

        boolean status = verifySing(sign, timestamp);
        if (status) {
            log.warn("web hook验签成功！");
            webHookService.updateStatus(request, jsonObj); // 支付|退款通知成功,更新订单记录
            return "success";
        } else {
            // return "fail";
            log.warn("web hook验签失败！");
            return null; // 不建议返回fail，保持沉默是更好的选择
        }

    }


}
